package cn.yunhe.control;

import cn.yunhe.entity.Myfriend;
import cn.yunhe.entity.User;
import cn.yunhe.server.FriendServer;
import cn.yunhe.server.UserServer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/DeleteFriendServlet")
public class DeleteFriendServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        //获取好友昵称
        String fuName = request.getParameter("fuName");
        //获取用户账号密码
        String username = (String) session.getAttribute("username");
        String password = (String) session.getAttribute("password");
        User user = new User(username, password);
        //新建server对象
        UserServer userServer = new UserServer();
        FriendServer friendServer = new FriendServer();
        //通过用对象获取用户全部信息
        User userAccount = userServer.login(user);
        List<User> list = userServer.getUser(fuName);
        if (list != null && list.size() > 0) {
            User userFriend = list.get(0);  //获取好友对象
            Myfriend myfriend1 = new Myfriend(userAccount.getuId(), userAccount.getuName(), userFriend.getuId(), userFriend.getuName());  //删除双重好友关系,确保好友的好友的列表中不存用户对象
            Myfriend myfriend2 = new Myfriend(userFriend.getuId(), userFriend.getuName(), userAccount.getuId(), userAccount.getuName());  //删除双重好友关系,确保好友的好友的列表中不存用户对象
            boolean flag1 = friendServer.DeleteFriend(myfriend1);
            boolean flag2 = friendServer.DeleteFriend(myfriend2);
            if (flag1 && flag2){
                request.setAttribute("result","好友删除成功!!");
                request.getRequestDispatcher("deleteFrend.jsp").forward(request,response);
            }else {
                request.setAttribute("result","好友删除失败,好友列表不存在该好友!!");
                request.getRequestDispatcher("deleteFrend.jsp").forward(request,response);
            }
        }else {
            request.setAttribute("result","该好友名不存在,请输入正确的好友名!!");
            request.getRequestDispatcher("deleteFrend.jsp").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
